#!/usr/bin/env python
#coding:utf-8
#
# Copyright 2010 Close To U.
#
# Author:Darcy<http://closetou.com>
#

import os
import datetime
import logging
import cgi
import hashlib
from settings import *
from models import *
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api import memcache, users

DEBUG = True

class BaseRequestHandler(webapp.RequestHandler):
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'user': users.get_current_user(),
      'is_admin':users.is_current_user_admin(),
      'login_url': users.create_login_url(self.request.uri),
      'logout_url': users.create_logout_url('/'),
      'debug': self.request.get('debug'),
      'version':VERSION
    }    
    site_theme = 'default'
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, 'templates', 'dashboard', template_name)
    self.response.out.write(template.render(path, values, debug=DEBUG))

class PhotosHandler(BaseRequestHandler):
  def get(self):
    
    values = {'secret':SECRET}
    self.generate('photos.html',values)
  def post(self):
    photo_file = self.request.POST['file']
    if isinstance(photo_file, cgi.FieldStorage):
      filesize = len(photo_file.value)
      if filesize > 0 and filesize < 1048576:#1024*1024
        hash_value = hashlib.sha1(photo_file.value).hexdigest()
        b = Blobs.getbyhash(hash_value)
        if not b:
          logging.info(photo_file.type)
          index = Accumulator.get_or_insert(key_name='Blobs', name='Blobs')
          index.counter +=1
          index.put()
          photo = Blobs(parent=index)
          photo.blob_id = index.counter
          photo.content_type = photo_file.type
          photo.filename = photo_file.filename
          photo.size = filesize
          photo.hash_value = hash_value
          photo.blob = photo_file.value
          photo.put()
          #self.redirect('/photo/'+str(photo.key()))
          self.redirect('/dashboard')
        else:
          self.response.out.write("file existed")

##    for key, value in self.request.params.items():
##        logging.info(key)
##        logging.info(value)
##        if isinstance(value, cgi.FieldStorage):
##          logging.info('xyz')
##          logging.info(value.filename)
##          logging.info(value.type)
##          logging.info(hashlib.md5(value.value).hexdigest())
    
def main():
  application = webapp.WSGIApplication([('/dashboard$', PhotosHandler)],
                                       debug=DEBUG)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
